import Flutter
import UIKit
import AVFoundation

// Add this extension to make FlutterError conform to Swift's Error protocol.
extension FlutterError: @retroactive Error {}

public class MultiCameraPlugin: NSObject, FlutterPlugin {
    private var nativeCameraManager: NativeCameraManager?
    private var flutterApi: MultiCameraFlutterApi?

    private static var currentInstance: MultiCameraPlugin?

    public static func getCurrentCameraManager() -> NativeCameraManager? {
        print("MultiCameraPlugin: getCurrentCameraManager() 被调用")
        print("MultiCameraPlugin: currentInstance = \(currentInstance != nil ? "存在" : "nil")")
        print("MultiCameraPlugin: nativeCameraManager = \(currentInstance?.nativeCameraManager != nil ? "存在" : "nil")")
        return currentInstance?.nativeCameraManager
    }

    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "multi_camera_plugin", binaryMessenger: registrar.messenger())
        let instance = MultiCameraPlugin()
        MultiCameraPlugin.currentInstance = instance
        registrar.addMethodCallDelegate(instance, channel: channel)

        // 注册PlatformView
        let factory = CameraPreviewViewFactory(messenger: registrar.messenger())
        registrar.register(factory, withId: "multi_camera_preview")

        // 设置Pigeon API
        MultiCameraHostApiSetup.setUp(binaryMessenger: registrar.messenger(), api: instance)
        instance.flutterApi = MultiCameraFlutterApi(binaryMessenger: registrar.messenger())
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)
        default:
            result(FlutterMethodNotImplemented)
        }
    }

    // MARK: - Private Methods

    private func getNativeCameraManager() -> NativeCameraManager {
        if nativeCameraManager == nil {
            print("MultiCameraPlugin: 创建新的NativeCameraManager实例")
            nativeCameraManager = NativeCameraManager()
        } else {
            print("MultiCameraPlugin: 重用现有的NativeCameraManager实例")
        }
        return nativeCameraManager!
    }
}

// MARK: - MultiCameraHostApi Implementation

extension MultiCameraPlugin: MultiCameraHostApi {

    func getCameraCapabilities(completion: @escaping (Result<CameraCapabilities, Error>) -> Void) {
        let manager = getNativeCameraManager()

        let capabilities = CameraCapabilities(
            supportedImplementations: [CameraImplementationType.native],
            hasFrontCamera: manager.hasFrontCamera(),
            hasBackCamera: manager.hasBackCamera(),
            hasFlash: manager.hasFlash(),
            hasZoom: false // 暂不支持变焦
        )

        completion(.success(capabilities))
    }
    
    // 原生权限检测方法
    func checkCameraPermissionNative(completion: @escaping (Result<Bool, Error>) -> Void) {
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            print("🔐 原生权限检查: 已授权")
            completion(.success(true))
        case .notDetermined:
            print("🔐 原生权限检查: 未确定，请求权限...")
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    print("🔐 原生权限请求结果: \(granted)")
                    completion(.success(granted))
                }
            }
        case .denied, .restricted:
            print("🔐 原生权限检查: 被拒绝或受限")
            completion(.success(false))
        @unknown default:
            print("🔐 原生权限检查: 未知状态")
            completion(.success(false))
        }
    }

    func initializeCamera(
        config: CameraConfig,
        implementationType: CameraImplementationType,
        completion: @escaping (Result<Void, Error>) -> Void
    ) {
        print("MultiCameraPlugin: 开始初始化摄像头，方向: \(config.lensDirection.rawValue)")
        let manager = getNativeCameraManager()

        let position: AVCaptureDevice.Position = {
            switch config.lensDirection {
            case .front:
                return .front
            case .back:
                return .back
            default:
                return .back
            }
        }()

        print("MultiCameraPlugin: 转换后的摄像头位置: \(position.rawValue)")

        manager.initialize(position: position) { [weak self] success, error in
            print("MultiCameraPlugin: 摄像头初始化回调 - 成功: \(success), 错误: \(error ?? "无")")
            if success {
                self?.flutterApi?.onCameraStatusChanged(status: .initialized) { _ in }
                completion(.success(()))
            } else {
                let cameraError = CameraError(
                    code: "INITIALIZATION_FAILED",
                    message: error ?? "初始化失败",
                    details: nil
                )
                self?.flutterApi?.onCameraError(error: cameraError) { _ in }
                completion(.failure(NSError(
                    domain: "MultiCameraPlugin",
                    code: -1,
                    userInfo: [NSLocalizedDescriptionKey: error ?? "初始化失败"]
                )))
            }
        }
    }

    func switchImplementation(
        implementationType: CameraImplementationType,
        completion: @escaping (Result<Void, Error>) -> Void
    ) {
        // 原生实现只支持一种类型，直接返回成功
        completion(.success(()))
    }

    func switchCamera(
        direction: CameraLensDirection,
        completion: @escaping (Result<Void, Error>) -> Void
    ) {
        let manager = getNativeCameraManager()

        let position: AVCaptureDevice.Position = {
            switch direction {
            case .front:
                return .front
            case .back:
                return .back
            default:
                return .back
            }
        }()

        // 由于AVFoundation的限制，我们需要重新初始化来切换摄像头
        manager.switchCamera { success, error in
            if success {
                completion(.success(()))
            } else {
                completion(.failure(NSError(
                    domain: "MultiCameraPlugin",
                    code: -2,
                    userInfo: [NSLocalizedDescriptionKey: error ?? "切换摄像头失败"]
                )))
            }
        }
    }

    func takePicture(completion: @escaping (Result<CaptureResult, Error>) -> Void) {
        let manager = getNativeCameraManager()

        manager.takePicture { imagePath, fileSize, error in
            if let imagePath = imagePath {
                let result = CaptureResult(
                    imagePath: imagePath,
                    timestamp: Int64(Date().timeIntervalSince1970 * 1000),
                    fileSize: fileSize
                )
                completion(.success(result))
            } else {
                completion(.failure(NSError(
                    domain: "MultiCameraPlugin",
                    code: -3,
                    userInfo: [NSLocalizedDescriptionKey: error ?? "拍照失败"]
                )))
            }
        }
    }
    
    func setFlashMode(mode: FlashMode, completion: @escaping (Result<Void, Error>) -> Void) {
        let manager = getNativeCameraManager()

        let flashMode: AVCaptureDevice.FlashMode = {
            switch mode {
            case .off:
                return .off
            case .on:
                return .on
            case .auto:
                return .auto
            case .torch:
                return .on // iOS中torch模式需要特殊处理，这里简化为on
            }
        }()

        manager.setFlashMode(flashMode)
        completion(.success(()))
    }

    func startPreview(completion: @escaping (Result<Void, Error>) -> Void) {
        // AVFoundation自动处理预览
        completion(.success(()))
    }

    func stopPreview(completion: @escaping (Result<Void, Error>) -> Void) {
        // AVFoundation自动处理预览
        completion(.success(()))
    }

    func dispose(completion: @escaping (Result<Void, Error>) -> Void) {
        nativeCameraManager?.dispose()
        nativeCameraManager = nil
        completion(.success(()))
    }

    func isImplementationAvailable(
        implementationType: CameraImplementationType,
        completion: @escaping (Result<Bool, Error>) -> Void
    ) {
        let manager = getNativeCameraManager()
        let isAvailable = manager.isAvailable()
        completion(.success(isAvailable))
    }

    // This method is for Android's texture-based rendering and is not supported on iOS.
    func createCameraTexture(completion: @escaping (Result<CameraTexture, Error>) -> Void) {
        let error = FlutterError(
            code: "UNSUPPORTED_OPERATION",
            message: "createCameraTexture is not supported on iOS.",
            details: nil
        )
        completion(.failure(error))
    }

    func pauseSession(completion: @escaping (Result<Void, Error>) -> Void) {
        let manager = getNativeCameraManager()
        manager.pauseSession()
        completion(.success(()))
    }

    func resumeSession(completion: @escaping (Result<Void, Error>) -> Void) {
        let manager = getNativeCameraManager()
        manager.resumeSession()
        completion(.success(()))
    }

    func isSessionPaused(completion: @escaping (Result<Bool, Error>) -> Void) {
        let manager = getNativeCameraManager()
        let isPaused = manager.isSessionPaused()
        completion(.success(isPaused))
    }
}
